/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

import * as fs from 'fs';

import { HvigorCommonConst } from '../common/options/common-const.js';
import { HvigorLogger } from '../log/hvigor-log.js';

export function readFile(filepath: string): Promise<Error | Buffer> {
  return new Promise((resolve, reject) => {
    fs.readFile(filepath, (err, data) => {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    });
  });
}

export function writeFile(filepath: string, data: string | NodeJS.ArrayBufferView): Promise<Error | void> {
  return new Promise((resolve, reject) => {
    fs.writeFile(filepath, data, (err) => {
      if (err) {
        reject(err);
      } else {
        resolve();
      }
    });
  });
}

/**
 * 如果路径不存在就报错并退出
 *
 * @param log 日志
 * @param path 待判断的路径
 * @param field 需要检查的字段
 * @param configFile 需要检查的配置文件
 */
export function exitIfNotExists(log: HvigorLogger, path: string, field: string, configFile: string): void {
  if (!fs.existsSync(path) || fs.realpathSync.native(path) !== path) {
    log.printErrorExit('PATH_NOT_FOUND', [path], [[field, configFile]]);
  }
}

/**
 * 寻找工程下hvigorfile文件的真实路径
 *
 * @param hvigorFilePath 不带后缀的hvigorfile文件路径
 * @param _log 日志工具
 * @returns {string | undefined} 寻找结果
 */
export function findRealHvigorFilePath(hvigorFilePath?: string, _log?: any): string | undefined {
  if (!hvigorFilePath) {
    return undefined;
  }
  for (const suffix of HvigorCommonConst.BUILD_FILE_NAME_SUFFIX) {
    const realHvigorFilePath = `${hvigorFilePath}${suffix}`;
    if (fs.existsSync(realHvigorFilePath)) {
      return realHvigorFilePath;
    }
  }
  _log?.printErrorExit('HVIGOR_FILE_NOT_FOUND',[`${hvigorFilePath}.ts`]);
  return undefined;
}
